package com.jinlejia.erp.ui.house;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.PhotoAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.SaveCookieBean;
import com.jinlejia.erp.databinding.ActivityInvestigationImageBinding;
import com.jinlejia.erp.ui.common.ImageViewPagerActivity;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DbUtil;
import com.jinlejia.erp.utils.RxUpLoad;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.Call;
import okhttp3.MediaType;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;

/**
 * 实勘图片
 */
public class InvestigationImageActivity extends AppCompatActivity {

    private ArrayList<String> mSelectPath = new ArrayList<>();
    private PhotoAdapter adapter;
    private ProgressDialog progressDialog;
    private JSONArray urlArray;

    private String isFirst;

    private ActivityInvestigationImageBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_investigation_image);


        binding.btBack.setOnClickListener(this::onClick);
        binding.btSubmit.setOnClickListener(this::onClick);

        isFirst = getIntent().getStringExtra("isFirst");

        if(isFirst.equals("1") ){
            binding.shikanDes.setVisibility(View.GONE);
        }else{
            binding.shikanDes.setVisibility(View.VISIBLE);
        }

        binding.inputContent.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = 200 - s.length();
                binding.textCount.setText(number + "/200");
                selectionStart = binding.inputContent.getSelectionStart();
                selectionEnd = binding.inputContent.getSelectionEnd();
                if (temp.length() > 200) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    binding.inputContent.setText(s);
                    binding.inputContent.setSelection(tempSelection);//设置光标在最后
                }
            }
        });

        binding.yfRecycler.setHasFixedSize(true);
        binding.yfRecycler.setLayoutManager(new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false));
        adapter = new PhotoAdapter(this, mSelectPath);
        binding.yfRecycler.setAdapter(adapter);

        adapter.setOnSelectClickLitener(() -> MultiImageSelector.create(InvestigationImageActivity.this)
                .showCamera(true)
                .count(10)
                .single()
                .multi()
                .origin(mSelectPath)
                .start(InvestigationImageActivity.this, 101));
        adapter.setOnDelClickLitener(p -> {
            mSelectPath.remove(p);
            adapter.notifyItemRemoved(p);
            adapter.notifyItemRangeChanged(p, mSelectPath.size() - p);
        });
        adapter.setOnItemClickLitener(i -> {
            Intent intent = new Intent(InvestigationImageActivity.this, ImageViewPagerActivity.class);
            intent.putStringArrayListExtra("imgs", (ArrayList<String>) mSelectPath);
            intent.putExtra("position", i + 1);
            startActivity(intent);
        });
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_submit:
                //提交
                if (TextUtils.isEmpty(binding.inputContent.getText().toString()) && isFirst.equals("0")) {
                    CustomToast.showToast(this, "请输入实勘说明", 1500);
                } else {
                    progressDialog = new ProgressDialog(InvestigationImageActivity.this, "上传中...");
                    progressDialog.show();

                    ArrayList<File> list = new ArrayList<>();
                    if (mSelectPath.size() > 0) {
                        for (int i = 0, j = mSelectPath.size(); i < j; i++) {
                            File file = new File(mSelectPath.get(i));
                            list.add(file);
                        }
                        if (list.size() > 0)
                            compressWithRx(list);
                    }
                }
                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                adapter.setDatas(mSelectPath);
            }
        }
    }

    /**
     * 压缩单张图片 RxJava 方式
     */
    private void compressWithRx(ArrayList<File> list) {
        urlArray = new JSONArray();
        Luban.get(this)
                .load(list)
                .putGear(Luban.THIRD_GEAR)
                .asObservable()
                .flatMap(new Func1<File, Observable<String>>() {
                    @Override
                    public Observable<String> call(File file) {
                        Map<String, String> header = new HashMap<>();
                        header.put("token", ACache.get(InvestigationImageActivity.this).getAsString("token") == null ? "" : ACache.get(InvestigationImageActivity.this).getAsString("token"));
//                        header.put("cookie", ACache.get(InvestigationImageActivity.this).getAsString("cookie") == null ? "" : ACache.get(InvestigationImageActivity.this).getAsString("cookie"));
                        header.put("cookie", null ==  DbUtil.getDB(InvestigationImageActivity.this).single().queryById(200, SaveCookieBean.class)  ? "" : DbUtil.getDB(InvestigationImageActivity.this).single().queryById(200, SaveCookieBean.class).getCookie());

                        return RxUpLoad.get(InvestigationImageActivity.this)
                                .url(ApiConfig.IMG_UPLOAD)
                                .file(file)
                                .fileName(System.currentTimeMillis() + ".jpg")
                                .key("uploadFile")
                                .header(header)
                                .asObservable();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        JSONObject jsonObject = JSON.parseObject(s);
                        if (jsonObject.get("code").toString().equals("200")) {
                            urlArray.add(jsonObject.get("data"));
                            if (urlArray.size() == mSelectPath.size()) {
                                submit();
                            }
                        } else {
                            if (null != progressDialog && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            CustomToast.showToast(InvestigationImageActivity.this, jsonObject.get("message").toString(), 1500);
                        }
                    }
                });
    }

    private void submit() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rscode", getIntent().getStringExtra("code"));
        jsonObject.put("list", urlArray.toString());
        jsonObject.put("reason", binding.inputContent.getText().toString());
        String url;
        if (getIntent().getStringExtra("type").equals("shs")) {
            url = ApiConfig.SHS_SAVE_IMAGE;
        } else {
            url = ApiConfig.RENT_SAVE_IMAGE;
        }

        OkHttpUtils
                .postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(InvestigationImageActivity.this, response, null)) {
                            setResult(RESULT_OK, new Intent());
                            CustomToast.showToast(getApplicationContext(), "保存成功", 1500);
                            finish();
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
